﻿import com.neshumah.Util.ObjectsList;import tv.zarate.Utils.Delegate;

//import com.gskinner.events.GDispatcher;
import mx.events.EventDispatcher;
class com.dxdesign.util.McLoader {	
	// define functions for EventDispatcher:
	public var dispatchEvent:Function;
	public var addEventListener:Function;
	public var removeEventListener:Function;
	
	private var mclist:ObjectsList;
	private var preloaderObjects:Array;
	private var intervalo:Number;
	var currentPercent:Number;
	
	static var notLoaded:Number = 0;
	static var loading:Number = 1;
	static var loaded:Number = 2;
		public function McLoader() {		
		this.mclist=new ObjectsList();
		this.preloaderObjects= new Array();
		//GDispatcher.initialize(this);	// setear el dispacher event
		EventDispatcher.initialize(this);
		this.currentPercent=0;
	}	
	public function addPath(path:String, holder:MovieClip){
		
		var elemento=new Object();
		elemento.path=path;
		elemento.holder=holder;
		elemento.loaded= McLoader.notLoaded;	
		
		this.mclist.add(elemento);
	}
	
	public function batchLoad():Void{
		var elem:Object;
		this.mclist.reset();	// resetear el index de la lista
		
		
		while(elem = this.mclist.next() ){
			if(elem.loaded == McLoader.notLoaded){
				elem.holder.loadMovie( elem.path );
				elem.loaded= McLoader.loading;
			}
		}
		this.starLoad();
	}
	
	public function starLoad(){
		this.intervalo= setInterval(Delegate.create(this, checkLoad) , 100 );
	}
	
	private function checkLoad():Void{
		
		var totalBytes:Number=0;
		var loadedBytes:Number=0;
		
		var total=new Array();
		var leido=new Array();
		
		var elem:Object;
		var i:Number;
		this.mclist.reset();
		
		while(elem = this.mclist.next() ){
			if(elem.loaded == McLoader.loading){
				total.push( elem.holder.getBytesTotal() );
				totalBytes+=elem.holder.getBytesTotal();
				leido.push( elem.holder.getBytesLoaded() );
				loadedBytes+=elem.holder.getBytesLoaded();
			}
		}
		
		
		//dispatchEvent({target:this, type:"eventFired", elapsedTime:getTimer()});
		//dispatchEvent({target:this,type:"complete",success:'1'});
		
		
		if(totalBytes && (totalBytes == loadedBytes)){
			trace("dispatch event");
			
			//dispatchEvent({target:this,type:"loadComplete",status:1});
			dispatchEvent({target:this,type:"complete",success:'2'});
			
			clearInterval(this.intervalo);
		}else{
			var p=Math.ceil( (loadedBytes * 100) /totalBytes  );
			//trace(p+" > "+this.currentPercent);
			if(p > this.currentPercent){
				//trace("on progress "+ p);
				dispatchEvent({target:this,type:"onProgress", percent: p });
				this.currentPercent=p;
			}
			
		}
	}
	}